package com.blog.wu.myblog.controller;

import com.blog.wu.myblog.base.BaseController;
import com.blog.wu.myblog.entity.LoginLog;
import com.blog.wu.myblog.entity.UserInfo;
import com.blog.wu.myblog.service.LoginLogService;
import com.blog.wu.myblog.service.UserInfoService;
import com.blog.wu.myblog.util.HttpUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * @Author wuyanshen
 * @Date 2018-11-05 10:25 AM
 * @Discription 描述
 */
@Controller
public class LoginController extends BaseController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private LoginLogService loginLogService;


    /**
     * 登录失败时调用，真正登录的POST请求由ShiroFormFilter完成
     *
     * @param user
     * @param model
     * @param request
     * @return java.lang.String
     * @Date 2018/11/5 2:49 PM
     * @Author wuyanshen
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String userLoginPost(UserInfo user, Model model, HttpServletRequest request) {
        logger.info("开始用户登录...");
        try {

            String message = (String) request.getAttribute("message");

            model.addAttribute("msg", message);

//            UserInfo userInfo = userInfoService.isLogin(user);
//            if (userInfo != null) {

            //添加认证用户
//            Subject subject = SecurityUtils.getSubject();
//            UsernamePasswordToken token = new UsernamePasswordToken(user.getUserAccount(),user.getUserPassword());
            //进行认证，这里可以捕获异常，返回对应的信息
//            subject.login(token);
//            UserInfo userInfo = userInfoService.isLogin(user);

//            UserInfo userInfo = (UserInfo) SecurityUtils.getSubject().getPrincipal();
//            Session session = subject.getSession();


//            return "back/index";
//            } else {
//
//                //记录登录信息
//                recordLogin(user, request, "0");
//
//                model.addAttribute("info", "账号或密码错误");
//                return "/back/login";
//            }
        } catch (UnknownAccountException e) {
            logger.info("用户名不存在【{}】", e.getMessage());
            model.addAttribute("msg", e.getMessage());
        } catch (IncorrectCredentialsException e) {
            logger.info("用户密码错误【{}】", e.getMessage());
            model.addAttribute("msg", "用户密码错误");
        } catch (AuthenticationException e) {
            logger.info("登录失败【{}】", e.getMessage());
        } finally {
            logger.info("用户登录结束...");
        }

        return "/back/login";
    }


    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String userLoginGet(UserInfo user, Model model, HttpServletRequest request, HttpSession session) {
        logger.info("进入了login get方法");

        return "/back/login";
    }


    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String index(Model model, HttpServletRequest request, HttpSession session) {
        logger.info("进入了index get方法");
        //记录登录信息
        UserInfo userInfo = (UserInfo) SecurityUtils.getSubject().getPrincipal();
        recordLogin(userInfo, request, "1");
        return "redirect:/back/index";
    }

    @RequestMapping("logout")
    public String login(HttpSession session) {
        logger.info("开始退出系统...");
        try {
            //清除session
//            session.invalidate();
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
            return "/back/login";
        } catch (Exception e) {
            logger.info("退出系统出错 {}", e.getMessage());
        } finally {
            logger.info("退出系统结束...");
        }
        return null;
    }

    /**
     * 记录登录信息
     *
     * @param userInfo
     * @param request
     * @param status
     * @return void
     * @Date 2018/10/15 上午11:06
     * @Author wuyanshen
     */
    private void recordLogin(UserInfo userInfo, HttpServletRequest request, String status) {
        logger.info("开始记录登录信息...");
        try {
            LoginLog loginLog = new LoginLog();
            loginLog.setLoginIp(HttpUtils.getIp(request));
            loginLog.setLoginTime(new Date());
            loginLog.setLoginName(userInfo.getUserName() == null ? "" : userInfo.getUserName());
            loginLog.setLoginAccount(userInfo.getUserAccount());
            loginLog.setLoginStatus(status);
            loginLogService.add(loginLog);
        } catch (Exception e) {
            logger.info("记录登录信息出错了: 【{}】", e.getMessage());
        } finally {
            logger.info("记录登录信息结束...");
        }

    }

}
